﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Wholesaler.Models.DBModels;
using Yunzuan.Common;
using Yunzuan.Common.Interface;
using Yunzuan.Common.Log;
using Yunzuan.Foundation.DataAccess;
using YunZuan.Models.Entities;
using Yunzuan.Foundation.Web;
using Yunzuan.Foundation.Web_api;
using YunZuan.Models;

namespace WholesalerService
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“SubService”。
    // 注意: 为了启动 WCF 测试客户端以测试此服务，请在解决方案资源管理器中选择 SubService.svc 或 SubService.svc.cs，然后开始调试。
    /// <summary>
    /// 给底下二级使用
    /// </summary>
    public class SubService : ISubService
    {

        public string QueryStock(string queryParam, string token)
        {
            CheckCustomerIDByToken(token, out string yijiCustomerID, out int customerID);
            if (customerID == 0)
                return CommonLog.MsgErrorInfo("客户信息不正确");
            HashParam param = JsonConvert.DeserializeObject<HashParam>(queryParam);
            int goodType = param.GetInt("GoodsType", 1); //默认裸钻
            param.Add(yijiCustomerID, customerID); //加入一级的customerid
            string result = string.Empty;
            if (goodType == 1)
            {
                param.Remove("GoodsType"); //裸钻批发里面不需要这个key
                result = CWholesalers.GetInventoryInfosByPF(JsonConvert.SerializeObject(param), token, param);
            }
            else
            {
                result = CWholesalers.GetProductData(JsonConvert.SerializeObject(param));
            }

            return result;
        }

        private void CheckCustomerIDByToken(string token, out string yijiCustomerID, out int customerID)
        {
            string customerId = "0";
            yijiCustomerID = "CustomerID";
            DecryptKey(token, yijiCustomerID, ref customerId); //解析一级customer出来
            int.TryParse(customerId, out customerID);
        }

        public string SubmitOrder(string queryParam, string token)
        {
            CheckCustomerIDByToken(token, out string yijiCustomerID, out int customerID);
            if (customerID == 0)
                return CommonLog.MsgErrorInfo("客户信息不正确");
            HashParam param = JsonConvert.DeserializeObject<HashParam>(queryParam);
            param.Add(yijiCustomerID, customerID); //加入一级的customerid
            var result = string.Empty;
            int goodType = param.GetInt("GoodsType", 1); //默认裸钻
            if (goodType == 1)
            {
                param.Remove("GoodsType"); //裸钻批发里面不需要这个key
                 result = SubmitOrdersByPF(param, queryParam);
            }
            else
            { 
                result = CWholesalers.SubmitOrderNew(JsonConvert.SerializeObject(param));
            }
            return result;
        }
        public  List<int> JArrayToIntArray(object obj)
        {
            List<int> ids = new List<int>();
            if (obj.GetType().ToString() == "Newtonsoft.Json.Linq.JArray") {
                Newtonsoft.Json.Linq.JArray jArray = (Newtonsoft.Json.Linq.JArray)obj;
                foreach (var item in jArray)
                {
                    ids.Add(Convert.ToInt32(item.ToString()));
                }
            }
            return ids;
        }
        public object objSubmitOrder = new object();
        private string SubmitOrdersByPF(HashParam param, string queryParam)
        {
            //代下单 {"CustomerID":"111","OrderType":2,"InventoryIDs":"16617637","Remarks":"xx"}
            //一级传key+secondsn
            var customerId = param.GetInt("CustomerID", 0);
            var orderType = param.GetInt("OrderType", 1);
            var inventoryIDs = param.GetString("ProductIDs");
            if (!(customerId > 0 && orderType > 0 && !string.IsNullOrEmpty(inventoryIDs)))
                return CommonLog.MsgErrorInfo("下单信息不正确");
            //用来操作移除非现货供应商的货
            if (param.ContainsKey("Remarks"))
                param["Remarks"] = $"{ param.GetString("SecondSN", "")}下单【二级】," + param.GetString("Remarks");
            else
                param.Add("Remarks", $"{ param.GetString("SecondSN", "")}下单【二级】");
            List<int> list = JArrayToIntArray(param["ProductIDs"]); //下单IDs
            if (list.Count == 0) return CommonLog.MsgErrorInfo("未选择任何订单");

            var tttagKey = string.Empty;
            if (param.ContainsKey("TagKey"))
            {
                tttagKey = param.GetString("TagKey");
                //param.Remove("TagKey");
            }
            else
                tttagKey = CommonUrl.getURL(param, queryParam, "提交订单");

            var iParam = new
            {
                ID = list.ToArray(),
                CustomerID = customerId, 
                TagKey= tttagKey,
                useDict=true,
            };
            var inventoryJson = CWholesalers.GetInventoryInfosByPF(JsonConvert.SerializeObject(iParam), "");
 
            if (inventoryJson == "")
                return CommonLog.MsgErrorInfo("获取信息失败，请重试");
            var submmitOrderParam = JsonConvert.SerializeObject(iParam);
            //格式化数据中心数据
            var anonymousData = JsonConvert.DeserializeAnonymousType(inventoryJson, new { data = new object() });
            PageList<InventoryInfoResult> _SoldInventoryInfos = JsonConvert.DeserializeObject<PageList<InventoryInfoResult>>(JsonConvert.SerializeObject(anonymousData.data));//转成PageList

            if (_SoldInventoryInfos != null && _SoldInventoryInfos.Data.Count > 0)
            {

                CustomerInfo _customerInfo = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(customerId);
                if(_customerInfo==null)
                    return CommonLog.MsgErrorInfo("获取客户信息失败，请重试");
                var failCount = 0;
                var successCount = 0;
                var failCount1 = 0;
                var successCount1 = 0;
                SysSettingInfo setting = GoodsType.GetSystemSetting(tttagKey, GoodsType.Diamond);
                var orderInfoMessage = string.Format("提交订单——设置信息 币种：{0},销售汇率：{1},采购汇率：{2},全局退点（白）：{3},全局退点（彩）：{4}，分组折扣（白）：{5},分组折扣（彩）：{6},分组倍率：{7}"
                                                                           , setting.CurrentSet, setting.Rate, setting.PurchaseExchangerate, setting.GlobalDiscountReturn, setting.GlobalFancyDiscountReturn, setting.Group4C, setting.GroupFancy4C, setting.GroupAmount);
                StringBuilder sbMsg = new StringBuilder();
                sbMsg.Append(orderInfoMessage + "\r\n");
                failCount = list.Count - _SoldInventoryInfos.Data.Count;
                if (failCount > 0)
                {
                    var IDs = _SoldInventoryInfos.Data.ToList().Select(p => (int)p.ID).ToList();
                    var newlist = list.Except(IDs).ToList<int>();
                    //去除list 中在数据中心已下架获取不存在的ID
                    list = list.Except(newlist).ToList<int>();
                }
                foreach (var item in _SoldInventoryInfos.Data)
                {
                    if (item.Supplier.ToUpper() != tttagKey)//留下的就是现货
                    {
                        list.RemoveAt(list.IndexOf(Convert.ToInt32(item.ID)));
                    }
                }

                StringBuilder tempSns = new StringBuilder();
                string banningStatus = GlobalConfig.BanningStatus;
                 
                List<int> listScuccess = new List<int>();
                lock (objSubmitOrder)
                {
                    foreach (var item in _SoldInventoryInfos.Data)
                    {
                        int failFlag = 0;
                        int successFlag = 0;
                        if (banningStatus.IndexOf(item.Status.Value.ToString()) >= 0 || item.OnShelves == 0)//3实验室 4保留5展会  上架状态
                        {
                            sbMsg.Append("提交订单失败,订单状态为:【" + AllPublic.GetStatus(item.Status.Value) + "】上架状态为(1上0下):【" + item.OnShelves + "】\r\n");
                            failCount1++;
                            continue;
                        }
                        //这个函数里面有删除一级购物车，如果是二级下单则不走删除一级购物车流程
                        OrderToPack(param, customerId, orderType, tttagKey,"二级", setting, sbMsg, _customerInfo, tempSns, ref failFlag, ref successFlag, item);
                        if (failFlag == 1)
                        {
                            failCount++;
                        }
                        if (successFlag == 1)
                        {
                            successCount++;
                            listScuccess.Add(item.ID.Value);
                        }
                    }
                }
                TransmissionOrderResult submitOrderResult = new TransmissionOrderResult(); 
                ////调用订单提交接口  下单 不走数据中心
                #region
                if (list.Count > 0 && successCount > 0) //还有现货，则提交
                {
                    try
                    {
                        submitOrderResult = AllPublic.OprationOrders(list.ToArray(), "add", tttagKey);//提交订单 InventoryID  (OprationOrders 包含了提交订单、删除订单 和获取订单)
                        orderInfoMessage = "提交到数据中心，返回结果：" + JsonConvert.SerializeObject(submitOrderResult);
                        sbMsg.Append(orderInfoMessage + "\r\n");
                        if ((submitOrderResult != null && submitOrderResult.Successful != null) || (submitOrderResult != null && submitOrderResult.Failed != null))
                        {
                            successCount1 = submitOrderResult.Successful.Length;
                            failCount1 = submitOrderResult.Failed.Length;
                        }
                        if (submitOrderResult == null || submitOrderResult.Successful == null || successCount1 > 0)
                        {
                            //提交成功的从list移除，list为要删除的本地订单列表
                            if (successCount1 > 0)
                            {
                                for (int i = 0; i < submitOrderResult.Successful.Length; i++)
                                {
                                    list.Remove(submitOrderResult.Successful[i]);
                                }
                            }
                            //网络或其它原因的失败也删除本地订单
                            else
                            {
                                successCount1 = -1;
                                failCount1 = -1;
                            }
                            //删除本地订单list.ToArray()
                            if (list.Count > 0)
                            {
                                HashParam _p = new HashParam();
                                _p.Add("InventoryIDs", list.ToArray()); //要移除的现货list
                                int _r = YZ.GetDatabase(tttagKey).Delete("Order.DelOrdersByInventoryIds", _p); //删除本地订单结果
                                if (_r == 0)  //出现删除未成功提交的订单失败则
                                {
                                    orderInfoMessage = "删除【提交数据中心失败的订单】失败，状态为2，3的失败InventoryID为：" + JsonConvert.SerializeObject(list);
                                    sbMsg.Append(orderInfoMessage + "\r\n");
                                }
                                else
                                {
                                    foreach (var item in list)
                                    {
                                        successCount--; //删除订单成功的数量对应减少
                                        orderInfoMessage = "删除订单成功，InventoryID为：" + list.ToArray();
                                        sbMsg.Append(orderInfoMessage + "\r\n");
                                    }
                                }
                            }
                        }
                        failCount = failCount1;
                        orderInfoMessage = "提交订单11，数据中心返回结果：" + JsonConvert.SerializeObject(submitOrderResult);
                        sbMsg.Append(orderInfoMessage + "\r\n");
                    }
                    catch (Exception ex)
                    {
                        //出了异常暂时将现货的所有id都归在fail下
                        list.ToArray().CopyTo(submitOrderResult.Failed, 0);
                        sbMsg.Append(orderInfoMessage + "\r\n");
                        CommonLog.GetMethodInfoAndWriteLogs(this.GetType(), ex, sbMsg.ToString());
                        successCount1 = -1;
                        failCount1 = -1;
                    }
                }
                #endregion
                if (successCount == 0 && successCount1 == 0 && failCount == 0 && failCount1 == 0)
                {
                    failCount = list.Count;
                }
                Dictionary<string, string> dictOtherSystemLoginInfo = new Dictionary<string, string>();
                
                if (successCount > 0)//成功则发送短信
                {
                    UserInfo userInfo = new UserInfo();
                    if (_customerInfo.SalesUserID != null)
                    {
                        userInfo = YZ.GetDatabase(tttagKey).Get<UserInfo>(_customerInfo.SalesUserID.Value);
                        if (userInfo != null)
                        {
                            #region
                            var snStr = tempSns.ToString();
                            if (userInfo.Mobile != null)
                            {
                                // > 10  有可能有国外号码
                                if (AllPublic.IsPhoneNo(userInfo.Mobile) && orderType == 1)
                                {
                                    CWholesalers.SendMsgAsync(userInfo.Mobile, userInfo.RealName, _customerInfo.NickName, snStr);
                                    //SendMsg(userInfo.Mobile, userInfo.RealName, _customerInfo.NickName, snStr);  //业务
                                    orderInfoMessage = "提交订单12 成功后发送消息给业务员，业务员信息:" + JsonConvert.SerializeObject(userInfo);
                                    sbMsg.Append(orderInfoMessage + "\r\n");
                                    CommonLog.SendMQMsg(tttagKey, "发送消息给业务员，业务员信息:" + JsonConvert.SerializeObject(userInfo));
                                }
                                if (AllPublic.IsPhoneNo(_customerInfo.Mobile) && orderType == 2) //客户 //string.IsNullOrEmpty(publicKey) 指不是开放接口，开放接口的客户是管理员，在原系统(分销系统)会以管理员身份发送
                                {
                                    CWholesalers.SendMsgAsync(_customerInfo.Mobile, "", "您", snStr);
                                    //SendMsg(_customerInfo.Mobile, "", "您", snStr);
                                    orderInfoMessage = "提交订单13 成功后发送消息给客户，客户信息:" + JsonConvert.SerializeObject(_customerInfo);
                                    sbMsg.Append(orderInfoMessage + "\r\n");
                                    CommonLog.SendMQMsg(tttagKey, "成功后发送消息给客户，客户信息:" + JsonConvert.SerializeObject(_customerInfo));
                                }
                                //if (userInfo.Mobile != _customerInfo.Mobile && userInfo.Mobile != tel && tel.Length > 10)
                                //    SendMsg(tel, "管理员", _customerInfo.NickName, snStr);//admin
                            }
                            #endregion
                        }
                        else
                        {
                            orderInfoMessage = "提交订单14 下单成功，发短信失败，客户对应的用户已不存在！客户对应的ID是:" + _customerInfo.SalesUserID.Value;
                            sbMsg.Append(orderInfoMessage + "\r\n");
                            CommonLog.GetMethodInfoAndWriteLogs(this.GetType(), null, "下单成功，发短信失败，客户对应的用户已不存在！");
                        }
                    }
                    else
                    {
                        Link link = YZ.GetDatabase(tttagKey).Get<Link>(1);//系统管理员号码
                        var tel = "";
                        if (link != null)
                            tel = link.Telphone.ToString();
                        if (tel.Length > 10 && AllPublic.IsPhoneNo(tel))
                        {
                            CWholesalers.SendMsgAsync(tel, "管理员", _customerInfo.NickName, tempSns.ToString());
                            //SendMsg(tel, "管理员", _customerInfo.NickName, tempSns.ToString());//admin 
                            orderInfoMessage = "提交订单15 发短信给管理员，管理员电话:" + tel + ";客户昵称:" + _customerInfo.NickName + "货号:" + tempSns.ToString();
                            sbMsg.Append(orderInfoMessage + "\r\n");
                            CommonLog.SendMQMsg(tttagKey, "成功后发送消息给管理员，管理员电话:" + tel + ";客户昵称:" + _customerInfo.NickName + "货号:" + tempSns.ToString());
                        }
                    }
                }
                //开放key存在则封装（相当于分销）需要的数据

                var msg = new
                {
                    Successful = successCount,
                    Successful1 = successCount1,
                    Failed = failCount,
                    Failed1 = failCount1,
                    SuccessList = listScuccess,//其实这里的现货字典才是所需要的，非现货可以不用理会
                    FailList = submitOrderResult.Failed
                };
                orderInfoMessage = JsonConvert.SerializeObject(msg);
                sbMsg.Append("提交订单16 成功，返回消息" + orderInfoMessage + "\r\n");
                return CommonLog.MsgSuccessObj(orderInfoMessage);
            } 
            return CommonLog.MsgErrorInfo("提交订单失败");
        }
        /// <summary>
        /// 打包封闭Order
        /// </summary>
        /// <param name="param"></param>
        /// <param name="customerId"></param>
        /// <param name="orderType"></param>
        /// <param name="tttagKey"></param>
        /// <param name="secondSn"></param>
        /// <param name="setting"></param>
        /// <param name="sbMsg"></param>
        /// <param name="_customerInfo"></param>
        /// <param name="tempSns"></param>
        /// <param name="failCount"></param>
        /// <param name="successCount"></param>
        /// <param name="item"></param>
        private void OrderToPack(HashParam param, int customerId, int orderType, string tttagKey,string secondSn, SysSettingInfo setting, StringBuilder sbMsg, CustomerInfo _customerInfo, StringBuilder tempSns, ref int failCount, ref int successCount, InventoryInfoResult item)
        {
            var _order = new OrderInfo() { InventoryID = item.ID, CertNo = item.CertNo };
            _order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.SelectOrderByInventoryID", _order);
            if (_order == null)  //防止重复正常的订单 12345为正常的订单
            {
                //赋值
                #region  本地订单 属性打包添加
                _order = new OrderInfo();
                _order.ActiveIP = param.GetString("ActiveIP");
                _order.CreateTime = DateTime.Now;//下单时间 
                _order.Remarks = param.GetString("Remarks"); //客户下单备注 (去除空格 255长度)
                _order.PurchaseExchangerate = GoodsType.GetPurchaseExchangeRate(setting);//采购汇率 
                if (item.Supplier.ToUpper() == tttagKey)
                {
                    //检查到货时间是否为空
                    if (!string.IsNullOrEmpty(item.ArrivalTime))
                    {
                        //现货
                        _order.OrderStatus = 3;//订单状态 3（待出货） 
                        _order.ArrivalTime = item.ArrivalTime;
                        _order.Arrival = 1;//
                    }
                    else
                    {
                        _order.OrderStatus = 2;
                    }
                    //现货特有  买入时间，到货时间，付款状态，备注，采购人
                    if (!string.IsNullOrEmpty(item.PurchaseTime))
                        _order.PurchaseTime = Convert.ToDateTime(item.PurchaseTime);//买入时间 
                    if (!string.IsNullOrEmpty(item.ShipTime))
                        _order.DeliveryTime = Convert.ToDateTime(item.ShipTime);//发货时间 2017-02-10 
                    _order.ReceiptStatus = item.ReceiptStatus;//付款状态
                    if (!string.IsNullOrEmpty(item.PurchaseAgent))
                    {
                        UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentIdByName", item.PurchaseAgent);
                        if (userinfo != null)
                            _order.PurchaseUserID = userinfo.UserID;
                    }
                    if (item.PurchaseExchange != null && item.PurchaseExchange.Value > 0)
                    {
                        _order.BuyExchangerate = item.PurchaseExchange.Value;
                    }
                    else
                    {
                        _order.BuyExchangerate = 0;
                    }
                }
                else
                {
                    _order.ReceiptStatus = 0;//付款状态
                                             //定货
                    _order.OrderStatus = 1;//订单状态 1（下单成功，采购中）
                }
                _order.CreateTime = DateTime.Now;//下单时间 
                _order.PaymentStatus = 0;//收款状态 0
                _order.CustomerID = customerId;
                _order.SalesUserID = Convert.ToInt32(_customerInfo.SalesUserID);//销售ID
                _order.OrderType = orderType;//订单类型 (1客主 2代客 3 录入 4 二级） 9-10
                _order.SN = item.SN;//货号
                _order.InventoryID = item.ID;//库存ID
                _order.OriginSN = item.OriginSN;//原货号
                _order.Weight = item.Weight;//重量
                _order.CertNo = item.CertNo;//证书号
                _order.SupplierCode=item.Supplier;//供应商
                _order.Color = item.Color;//颜色
                _order.Clarity = item.Clarity;//净度
                _order.Symmetry = item.Symmetry;//对称
                _order.Polish = item.Polish;//抛光
                _order.IsFancy = item.IsFancy;//是否彩钻
                _order.CertType = item.CertType;//证书类型
                _order.Fluorescence = item.Fluorescence;//荧光
                _order.Place = item.Place;//所在地
                _order.Milky = item.Milky;//奶油
                _order.BlackDefect = item.BlackDefect;//黑点
                _order.Hue = item.Hue;//色调
                _order.HA = item.HA;//心箭
                _order.OtherDefect = item.OtherDefect;//其他瑕疵
                _order.EyeClean = item.EyeClean;//肉眼干净
                _order.Measurement = item.Measurement;//尺寸  
                _order.Shape = item.Shape;//形状
                _order.Cut = item.Cut;//切工
                _order.Rapnet = item.Rapnet;//国际报价（数据中心订单Rapnet始终为null）
                _order.Status = item.Status;//货品状态 8-19 
                _order.PurchaseSupplier = item.PurchaseSupplier;//采购供应商
                                                                //_order.PurchaseAgent= item.PurchaseAgent; 
                _order.PriceUSD = Math.Round(item.SourceDolarPerGrain.Value, 3);//买入美金总价
                _order.PurchaseRMB = Math.Round(_order.PriceUSD.Value * _order.PurchaseExchangerate.Value);
                _order.ConfirmUSD = Math.Round(item.CustomerDolarPerGrain.Value * _customerInfo.Discounts.Value, 3);//卖出美金 = 客户美金总价 2017-01-19

                _order.DiscountReturn = item.SourceDiscountReturn;//买入退点
                _order.MediaID = item.MediaID;
                _order.HasImage = item.HasImage;
                _order.HasVideo = item.HasVideo;
                _order.HasAtlas = item.HasAtlas;
                //卖出价格
                _order.SalesExchangerate = GoodsType.GetRate(setting);//销售汇率 
                _order.ConfirmPrice = Math.Round(_order.ConfirmUSD.Value * _order.SalesExchangerate.Value);//最后成交卖出人民币总价 *优惠

                _order.Confirmdiscount = AllPublic.CalcWhiteReturnPoint(_order.IsFancy, _order.ConfirmUSD, _order.Rapnet, _order.Weight, _customerInfo.Discounts, _order.PriceUSD);//最后成交退点
                                                                                                                                                                                   //新增原供应商
                _order.PurchaseSupplier = item.PurchaseSupplier;
                if (_order.SupplierCode.ToUpper() == tttagKey)
                {
                    _order.BuyDis = item.PurchaseDiscountReturn.Value;
                    _order.BuyRMBPrice = item.PurchaseRMB.Value;
                    _order.BuyUSDPrice = item.PurchaseUSDPerGrain.Value;
                }

                #endregion
                using (ITransaction trans_addOrder = YZ.GetTransaction(tttagKey))
                {
                    //执行
                    #region  执行事物，删除购物车
                    try
                    {
                        ///addOrderResult为返回的orderId
                        int addOrderResult = trans_addOrder.Add(_order);//生成单条订单 
                                                                        //单条订单生成成功,就移除购物车。
                        if (addOrderResult > 0)
                        {
                            tempSns.Append(_order.SN);
                            if (secondSn == "") //说明是一级下单，否则二级下单不用删除一级购物车
                            {
                                //删除购物车中的商品
                                int[] cartIds = { (int)item.ID };//这个是用来批量删除购物车的id
                                CommonCart.DelCartInfo(GoodsType.Diamond, tttagKey, param.GetInt("CustomerID"), cartIds);
                            }
                            trans_addOrder.CommitTransaction(); //当购物车移除成功，就同时触发生成本地订单和移除购物车（这个东西有效，可利用）
                            successCount++;
                        }
                    }
                    catch (Exception ex)
                    {
                        failCount++;
                        CommonLog.GetMethodInfoAndWriteLogs(this.GetType(), ex);
                        sbMsg.Append("提交订单异常]" + JsonConvert.SerializeObject(_order) + "异常信息==>" + ex.StackTrace + "参数:" + JsonConvert.SerializeObject(param) + "\r\n");

                    }
                    #endregion
                }
            }
            else
            {
                sbMsg.Append("已经存在的订单:" + item.ID + "\r\n");
                failCount++;
            }
        }

        private bool DecryptKey(string key, string refKey, ref string val)
        {
            bool isKey = false;
            try
            {
                if (key.Contains("_"))
                {
                    var padNum = 0; //去掉的=位数 ,
                    var num = key.Substring(key.LastIndexOf("_")).Replace("_", "");
                    int.TryParse(num, out padNum);
                    key = key.Substring(0, key.LastIndexOf("_")); //去掉占位两位（_x） 后再计算

                    key = Encoding.UTF8.GetString(Convert.FromBase64String(key.PadRight(key.Length + padNum, '=')));
                    var decryptObj = WXBizMsgCrypt.Decrypt(key);
                    var decryptCustomer = decryptObj.Split('_');
                    if (decryptCustomer.Length == 4)
                    {
                        var expirationTime = decryptCustomer[3];
                        DateTime.TryParse(expirationTime, out DateTime d);

                        if (d.CompareTo(DateTime.Now) >= 0)
                        {

                            if (refKey == "Supplier")
                            {
                                isKey = true;
                                val = decryptCustomer[2];
                            }
                            else if (refKey == "CustomerID")
                            {
                                if (decryptCustomer[0] == "")
                                {
                                    //key用了管理员分配的key
                                }
                                else
                                {
                                    val = decryptCustomer[0];
                                    isKey = true;
                                }
                            }
                            else
                            {
                                //无效的refKey
                            }
                        }
                        else
                        {  //过期

                        }
                    }
                    else
                    {
                        //解密不对

                    }
                }
                else
                {
                    //格式不对
                }
            }
            catch (Exception ee)
            {

                throw;
            }

            return isKey;
        }
    }
    public class WXBizMsgCrypt
    {
        private static string key = "a1234567";
        private static string iv = "A1234567";

        public static string Encrypt(string data)
        {
            string result = string.Empty;
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider()
            {
                Key = Encoding.ASCII.GetBytes(key),
                IV = Encoding.ASCII.GetBytes(iv)
            };
            using (MemoryStream memory = new MemoryStream())
            {
                using (CryptoStream crypto = new CryptoStream(memory, provider.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    crypto.Write(bytes, 0, bytes.Length);
                }
                result = Convert.ToBase64String(memory.ToArray());
                //result = Encoding.UTF8.GetString(memory.ToArray());

            }
            return result;
        }

        public static string Decrypt(string data)
        {
            string result = string.Empty;
            byte[] bytes = Convert.FromBase64String(data);
            //byte[] bytes = Encoding.UTF8.GetBytes(data);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider()
            {
                Key = Encoding.ASCII.GetBytes(key),
                IV = Encoding.ASCII.GetBytes(iv)
            };
            using (MemoryStream memory = new MemoryStream())
            {
                using (CryptoStream crypto = new CryptoStream(memory, provider.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    crypto.Write(bytes, 0, bytes.Length);
                }
                result = Encoding.UTF8.GetString(memory.ToArray());
            }
            return result;
        }
    }
}
